<?php
/**
 * Logging library
 *
 * Contains all code needed for logging.
 * @package Packages
 */

/**
 *
 */
require_once(AD_SERVER_PATH . '/pkgs/init.php');
require_once(AD_SERVER_PATH . '/pkgs/utils.php');

/**
 * Logging library
 *
 * Contains all code needed for logging.
 * @package Packages
 */
class CLogger
{
	/**
	 * Creates needed log
	 *
	 * Makes sure that log file passed as an argument exists.
	 * @param string $file
	 */
	public static function create_log($file)
	{
		if (!is_file($file))
		{
			CUtils::write_file($file, '', 'w');
		}
	}

	/**
	 * Creates needed logs
	 *
	 * Loops through and makes sure that all log files exist.
	 * @param array $ar
	 */
	public static function create_logs($ar)
	{
		foreach ($ar AS $file)
		{
			CLogger::create_log($file);
		}
	}

	/**
	 * Deletes old logs
	 *
	 * Loops through and cleans up any old log files.
	 * @param array $ignore_file_ar
	 * @param string $path
	 */
	public static function clean_logs($ignore_file_ar, $path)
	{
		$root_obj = dir($path);

		while ($file_name = $root_obj->read())
		{
			$cur_file = $path . $file_name;
			if (($file_name != '.') && ($file_name != '..'))
			{
				if (!in_array($cur_file, $ignore_file_ar))
				{
					unlink($cur_file);
				}
			}
		}
		$root_obj->close();
	}

	/**
	 * Get log list
	 *
	 * Gets list of valid log files.
	 * @return array $log
	 */
	public static function get_log_list()
	{
		for ($i = 0; $i < AD_DAYS_TO_KEEP_LOG; $i++)
		{
			$log[$i] = AD_DEBUG_FOLDER . 'ad_activity_' . date('Y_m_d', strtotime(-$i . 'days')) . '.log';
		}
		return $log;
	}

	/**
	 * Log action
	 *
	 * Writes action to todays log.
	 * @param string $level
	 * @param string $user
	 * @param string $msg
	 */
	public static function log($level, $user, $msg)
	{
		$log = CLogger::get_log_list();

		if (AD_LOGGING_LEVEL == 'DEBUG' || AD_LOGGING_LEVEL == $level)
		{
			CUtils::write_file($log[0], date('Y-m-d H:i:s') . ',' . $level . ',' . $user . ',' . CLogger::get_ip() . ',' . $msg . "\r\n", 'a');
		}
	}

	/**
	 * Get user IP
	 *
	 * Gets users IP address and returns it to caller.
	 * @return string $ip
	 */
	public static function get_ip()
	{
		if (isset($_SERVER['REMOTE_ADDR']))
		{
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
		{
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}
		else if (isset($_SERVER['HTTP_CLIENT_IP']))
		{
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		}
		else //
		{
			$ip = '';
		}
		return $ip;
	}
}
